﻿using Audit.Core;
using Dapper_Core.BLL.Interface;
using Dapper_Core.Common;
using Dapper_Core.DAL.Impl;
using Dapper_Core.Model;
using Dapper_Core.Table;
using ExpressionToWhere;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace Dapper_Core.BLL.Impl
{
    public class Sys_EmailTemplateBusiness: BaseRepository<Sys_EmailTemplate>, ISys_EmailTemplateBusiness
    {
        public Sys_EmailTemplateBusiness()
        {

        }

        public Sys_EmailTemplateBusiness(TransactionContext transactionContext) : base(transactionContext)
        {

        }

        public bool IsExist(string templateCode, string templateName)
        {
            try
            {
                if (string.IsNullOrEmpty(templateCode) || string.IsNullOrEmpty(templateName)) return true;
                Expression<Func<Sys_EmailTemplate, bool>> exp = model => model.TemplateCode == templateCode || model.TemplateName == templateName;
                List<Sys_EmailTemplate> list = base.GetList(exp, false).ToList();
                if (list != null && list.Count > 0) return true;
                return false;
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(MethodBase.GetCurrentMethod().DeclaringType.FullName, "检查邮件模板是否存在失败", "templateCode=" + templateCode + "，templateName=" + templateName, ex, "DapperCore");
                return false;
            }
        }

        public bool Add(Sys_EmailTemplate emailTemplate)
        {
            using (AuditScope scope = AuditScope.Create("Sys_EmailTemplate:Add", () => emailTemplate))
            {
                try
                {
                    scope.Comment("添加单个邮件模板");
                    scope.SetCustomField("Module", "Sys_EmailTemplate");
                    scope.SetCustomField("Operator", SessionUtility.GetBasicUserInfo().PinyinCode);
                    scope.SetCustomField("Operation", Operation.Insert);
                    bool success = base.Add(emailTemplate);
                    if (!success)
                    {
                        scope.Discard();
                    }
                    return success;
                }
                catch (Exception ex)
                {
                    scope.Discard();
                    NlogUtility.WriteError(MethodBase.GetCurrentMethod().DeclaringType.FullName, "邮件模板添加失败", "emailTemplate=" + JsonConvert.SerializeObject(emailTemplate), ex, "DapperCore");
                    return false;
                }
            }
        }

        public bool UpdateNotNull(Sys_EmailTemplate emailTemplate)
        {
            Sys_EmailTemplate old = base.Get(emailTemplate.Id);
            using (AuditScope scope = AuditScope.Create("Sys_EmailTemplate:Edit", () => old))
            {
                try
                {
                    scope.Comment("编辑邮件模板");
                    scope.SetCustomField("Module", "Sys_EmailTemplate");
                    scope.SetCustomField("Operator", SessionUtility.GetBasicUserInfo().PinyinCode);
                    scope.SetCustomField("Operation", Operation.Update);
                    old = emailTemplate;
                    bool success = base.UpdateNotNull(emailTemplate);
                    if (!success)
                    {
                        scope.Discard();
                    }
                    return success;
                }
                catch (Exception ex)
                {
                    scope.Discard();
                    NlogUtility.WriteError(MethodBase.GetCurrentMethod().DeclaringType.FullName, "邮件模板修改失败", "emailTemplate=" + JsonConvert.SerializeObject(emailTemplate), ex, "DapperCore");
                    return false;
                }
            }
        }

        public bool Delete(string ids, string deleter)
        {
            using (AuditScope scope = AuditScope.Create("Sys_EmailTemplate:Delete", () => ids))
            {
                try
                {
                    if (string.IsNullOrEmpty(ids)) return true;
                    List<string> idList = ids.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                    if (idList.Count < 1) return true;
                    scope.Comment("软删除邮件模板");
                    scope.SetCustomField("Module", "Sys_EmailTemplate");
                    scope.SetCustomField("Operator", deleter);
                    scope.SetCustomField("Operation", Operation.Delete);
                    //定义时间变量，保证同一次删除数据的删除时间相等
                    DateTime dateTime = DateTime.Now;
                    Expression<Func<Sys_EmailTemplate, bool>> exp = model => model.Id.In(idList);
                    bool success = base.SoftDelete(exp, deleter, dateTime);
                    if (!success)
                    {
                        scope.Discard();
                    }
                    return success;
                }
                catch (Exception ex)
                {
                    scope.Discard();
                    NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "邮件模板软删除失败", "ids=" + ids, ex, "DapperCore");
                    return false;
                }
            }
        }

        public (List<Sys_EmailTemplate> roles, int count) GetPageList(int pageIndex, int rowsPerPage, Sys_EmailTemplate emailTemplate, string orderby)
        {
            try
            {
                if (pageIndex < 0 || rowsPerPage < 1)
                {
                    return (new List<Sys_EmailTemplate>(), 0);
                }
                Expression<Func<Sys_EmailTemplate, bool>> exp = model => model.TemplateCode.Contains(emailTemplate.TemplateCode) && model.TemplateName.Contains(emailTemplate.TemplateName)
                                                                         && model.CreateDate < (emailTemplate.CreateDateEnd == null ? emailTemplate.CreateDateEnd : ((DateTime)emailTemplate.CreateDateEnd).AddDays(1))
                                                                         && model.CreateDate > emailTemplate.CreateDateStart && model.TemplateTitle.Contains(emailTemplate.TemplateTitle)
                                                                         && model.IsDeleted == 0;
                List<Sys_EmailTemplate> roles = base.GetPagelist(pageIndex + 1, rowsPerPage, exp, orderby).ToList();
                int count = base.GetListCount(exp);
                NlogUtility.WriteInfo(MethodBase.GetCurrentMethod().DeclaringType.FullName, "查询邮件模板分页信息", "pageIndex=" + pageIndex + "，rowsPerPage=" + rowsPerPage + "，emailTemplate=" + JsonConvert.SerializeObject(emailTemplate) + "，orderby=" + orderby, "DapperCore");
                return (roles, count);
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "获取邮件模板分页信息失败", "pageIndex=" + pageIndex + "，rowsPerPage=" + rowsPerPage + "，emailTemplate=" + JsonConvert.SerializeObject(emailTemplate), ex, "DapperCore");
                return (new List<Sys_EmailTemplate>(), 0);
            }
        }
    }
}
